from flask import render_template
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder import ModelView, ModelRestApi

from app.models import AppTarget, AppControlclass, AppComputeclass
from app.zsq import  defindAttribute
from . import appbuilder, db

"""
    Create your Model based REST API::

    class MyModelApi(ModelRestApi):
        datamodel = SQLAInterface(MyModel)

    appbuilder.add_api(MyModelApi)


    Create your Views::


    class MyModelView(ModelView):
        datamodel = SQLAInterface(MyModel)


    Next, register your Views::


    appbuilder.add_view(
        MyModelView,
        "My View",
        icon="fa-folder-open-o",
        category="My Category",
        category_icon='fa-envelope'
    )
"""

"""
    Application wide 404 error handler
"""


@appbuilder.app.errorhandler(404)
def page_not_found(e):
    return (
        render_template(
            "404.html", base_template=appbuilder.base_template, appbuilder=appbuilder
        ),
        404,
    )

class TargetModelApi(ModelRestApi):
    resource_name = 'target'
    datamodel = SQLAInterface(AppTarget)

appbuilder.add_api(TargetModelApi)
@defindAttribute
class TargetView(ModelView):
    datamodel = SQLAInterface(AppTarget)
    # dict = {}
    # cols = datamodel.list_columns
    # for col in cols:
    #     if(len(cols[col].foreign_keys)!=0 and cols[col].comment is not None):
    #         for fk in cols[col].foreign_keys:
    #           dict.__setitem__(fk._colspec.split('.')[0], cols[col].comment)
    #     elif(cols[col].comment is not None):
    #         dict.__setitem__(col,cols[col].comment)
    # label_columns = dict
    # lst = list(dict.keys())
    # list_columns = lst
    # show_columns= lst
    # add_columns= lst
    # edit_columns= lst
@defindAttribute
class ControlClassView(ModelView):
    datamodel = SQLAInterface(AppControlclass)
@defindAttribute
class ComputeclassView(ModelView):
    datamodel = SQLAInterface(AppComputeclass)

db.create_all()

appbuilder.add_view(
    TargetView,
    "指标定义",
    icon = "fa-folder-open-o",
    category = "指标管理",
    category_icon = "fa-envelope"
)
appbuilder.add_view(
    ControlClassView,
    "控制类型定义",
    category = "指标管理"
)
appbuilder.add_view(
    ComputeclassView,
    "计算类型定义",
    category = "指标管理"
)